import axios from 'axios'
import { ElMessage } from 'element-plus'
import Cookie from 'js-cookie'
import { AUTH } from '@/utils/constants.js'

const service = axios.create({
	baseURL: import.meta.env.VITE_APP_API,
	timeout: 1500,
})

/****** request拦截器==>对请求参数做处理 ******/
service.interceptors.request.use(
	(config) => {
		const auth = Cookie.get(AUTH)
		if(auth) {
			config.headers['Authorization'] = auth
		}
		return config
	},
	(error) => {
		//请求错误处理

		Promise.reject(error)
	}
)

/****** respone拦截器==>对响应做处理 ******/
service.interceptors.response.use(
	(response) => {
		//成功请求到数据

		if (response.data.code === 0) {
			return response.data
		} else {
			ElMessage.error(response.data.msg);
			console.log(response.data)
		}
	},
	(error) => {
		//响应错误处理
		console.log('error')
		console.log(error)
		console.log(JSON.stringify(error))

		return Promise.reject(error)
	}
)

export default service
